<?php

namespace frontend\controllers;

use backend\models\Goods;
use frontend\models\Cart;
use frontend\models\Address;
use frontend\models\OrderDetail;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use yii\db\Exception;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use EasyWeChat\Payment\Order;
use EasyWeChat\Foundation\Application;

class OrderController extends \yii\web\Controller
{
    public $layout = 'base';
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function behaviors()
    {
        //添加简单访问控制acf
        return [
            'acf'=>[
                'class'=>AccessControl::className(),
                'rules'=>[
                    [
                        'allow'=>true,
                        'actions'=>['add-order','list','notice','pay-by-wechat'],
                        'roles'=>['@'],
                    ]
                ]
            ]
        ];
    }

    /**
     * @return string
     * @throws Exception
     */
    public function actionAddOrder()
    {
        $model = new \frontend\models\Order();
		$member_id  = \Yii::$app->user->id;
		$carts = Cart::find()->where(['member_id'=>$member_id])->all();	
		
		if($model->load(\Yii::$app->request->post()) && $model->validate()){

		    /*
			public 'address_id' => string '0' (length=1)
			public 'delivery' => string '3' (length=1)
		`	public 'pay_id' => string '4'
		    * @property integer $id
 * @property string $member_id
 * @property string $name
 * @property string $province_name
 * @property string $city_name
 * @property string $area_name
 * @property string $detail_address
 * @property string $tel
 * @property string $delivery_id
 * @property string $delivery_name
 * @property string $delivery_price
 * @property string $pay_type_id
 * @property string $pay_type_name
 * @property string $price
 * @property integer $status
 * @property string $trade_no
 * @property integer $create_time
 * @property integer $update_timevar_dump($model);exit;
		@property string $member_id
			*/
            //address object
            $address = Address::findOne(['id'=>$model->address_id]);

			$model->member_id = \Yii::$app->user->id;
			$model->name= $address->username;
			$model->province_name = $address->province_name;
			$model->city_name =$address->city_name;
			$model->area_name = $address->area_name;
			$model->detail_address = $address->detail_address;
			$model->tel = $address->mobilephone;
			$model->delivery_id = $model->delivery;
			$model->delivery_price = \frontend\models\Order::$deliveries[$model->delivery]['price'];
			$model->delivery_name = \frontend\models\Order::$deliveries[$model->delivery]['delivery_name'];
			$model->pay_type_id = $model->pay_id;
			$model->pay_type_name  = \frontend\models\Order::$payMethod[$model->pay_id]['name'];
			//获取所有的购物车中的商品的信息
            $total = 0;
            $goods = [];
			foreach($carts as $cart){
			    /** @var  $cart \frontend\models\Cart */
			    $goods_id = $cart->goods_id;
			    $total += (integer)$cart->amount*$cart->goods->shop_price;
            }
            $model->price = $total;
            $model->trade_no =

            $model->status = 1;//未支付
            $model->create_time = time();
            $model->update_time=time();
            //订单编号 格式 y-m-d
            $model->trade_no = date('ymd').uniqid();
            $transaction = \Yii::$app->db->beginTransaction();//开启事物
            $message = false;//保存错误的提示信息;
            //捕获异常
            try{
                $model->save();
                //订单保存成功后保存购物车中的商品的信息到订单详情表中
                foreach($carts as $cart){
                    $order_detail = new OrderDetail();
                    $order_detail->order_info_id = $model->id;
                    $order_detail->goods_id = $cart->goods_id;
                    $order_detail->goods_name = $cart->goods->name;
                    $order_detail->logo = $cart->goods->logo;
                    $order_detail->price = $cart->goods->shop_price;
                    if($cart->amount > $cart->goods->stock){
                        throw new Exception('商品库存不足，请重新下单');
                    }
                    $order_detail->total_price = $cart->amount*$order_detail->price;
                    $order_detail->amount = $cart->amount;
                    //更新商品的库存
                    $cart->goods->stock = $cart->goods->stock-$cart->amount;
                    //保存商品的信息
                    $cart->goods->save();
                    //保存订单详情
                    $order_detail->save();
                    //清空购物车中的该商品的数据
                    $cart->delete();

                }
                //提交事物
                $transaction->commit();

            }catch (Exception $exception){
                $transaction->rollBack();//回滚事物
                //throw $exception;//再次抛出捕获的异常
                $message =  $exception->getMessage();
                \Yii::$app->session->setFlash('message',$message);
            }


			//跳转到提示订单提交成功或失败的提示页面
            return $this->redirect(['order/notice']);


		}


        return $this->render('orderadd',['model'=>$model,'carts'=>$carts]);

    }

    public function actionNotice(){
        $message = \Yii::$app->session->getFlash('message');
        return $this->render('notice',['message'=>$message]);
    }

    public function actionList(){
        $member_id = \Yii::$app->user->id;
        //得到该用户的所有的订单
        $models = \frontend\models\Order::find()->where(['member_id'=>$member_id])->all();

        //显示订单列表
        return $this->render('list',['models'=>$models]);
    }



    /*
     * 微信支付
     */
    public function actionPayByWechat($id){

        $order = \frontend\models\Order::findOne(['id'=>$id]);

        //更新订单的修改时间
        $order->update_time = time();
        $order->update();
        $body = '';
        foreach($order->getOrderDetail() as $detail){
            $body .= $detail->goods_name.'  ';
        }
        $detail = $body;

        $noticeUrl = Url::to(['order/response-wechat'],true);


        $app = new Application(\Yii::$app->params['wechat']);

        $payment = $app->payment;



        $attributes = [
            'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
            'body'             => "body",
            'detail'           => 'iPad mini 16G 白色',
            'out_trade_no'     => "{$order->trade_no}",
            'total_fee'        => $order->price*100, // 单位：分
            'notify_url'       => "{$noticeUrl}", // 支付结果通知网址，如果不设置则会使用配置里的默认地址
           // 'openid'           => '当前用户的 openid', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];

        $order = new Order($attributes);
        //调用统一下单接口创建订单
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
        }
        var_dump($result);


    }

    public function actionResponseWechat(){

        $app=  new Application(\Yii::$app->params['wechat']);

        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = \frontend\models\Order::findOne(['trade_no'=>$notify->out_trade_no]);
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order->status !=1) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                $order->update_time = time(); // 更新支付时间为当前时间
                $order->status = 2;
            } else { // 用户支付失败
                //$order->status = 'paid_fail';
            }
            $order->save(); // 保存订单
            return true; // 返回处理完成
        });
        return $response;
    }
}
